package com.company.site.vote;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.http.protocol.HTTP;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.WebUtils;

import com.company.base.utils.CheckUtil;
import com.company.base.utils.DateUtil;
import com.company.base.utils.ImageCompressUtil;
import com.company.site.mode.vote.Lottery;
import com.company.site.mode.vote.Player;
import com.company.site.mode.vote.Statistics;
import com.company.site.mode.vote.Vote;
import com.company.site.mode.wechatuser.WechatUser;
import com.company.site.user.UserService;


@Controller
@RequestMapping("")
public class VoteController{
	
	@Resource
	UserService userService;
	@Resource
	VoteService voteService;
	
	//投票首页
	@RequestMapping(value="vote")
	public String vote( String openid,Player player,Model model,HttpServletRequest request,String msg) throws UnsupportedEncodingException{
		//测试用
//		WebUtils.setSessionAttribute(request, "openid", "oDKLWs7mryL7Koln-t8FGqu-qNh4");
		
//		if (!CheckUtil.isEmpty(player.getKey())) {
//			player.setKey(new String(player.getKey().getBytes("ISO-8859-1"),"UTF-8"));
//			model.addAttribute("key", player.getKey());
//		}
		
//		String openid=(String) WebUtils.getSessionAttribute(request, "openid");
/*		WechatUser wechatUser=userService.getUserInfoByOpenid(openid);
		if (CheckUtil.isEmpty(wechatUser)||wechatUser.getSubscribe().equals(0)) {
			System.out.println("未关注的用户！");
			model.addAttribute("error", "error");
		}*/
		voteService.addTotalVisted();
		Statistics statistics=voteService.findStatistics();
		List<Player> list = voteService.findPlayerInfo(player);
		model.addAttribute("list", list);
		model.addAttribute("totalPlayer", statistics.getTotalPlayer());
		model.addAttribute("totalVisted", statistics.getTotalVisted());
		model.addAttribute("totalVoted", statistics.getTotalVoted());
		//String openid=(String) WebUtils.getSessionAttribute(request, "openid");
		model.addAttribute("openid", openid);
		model.addAttribute("id", player.getId());
		model.addAttribute("msg", msg);
		
		return "vote/vote";
	}
	
	//进行投票
	@RequestMapping(value="doVote",produces="application/text;charset=utf-8")
	@ResponseBody
	public String doVote(Long id,HttpServletRequest request) throws ParseException{
//		String openid=(String) WebUtils.getSessionAttribute(request, "openid");
		String openid="oQSRbuHYciRcHXmFAEwRJmnKeVzY";

//		Statistics statistics=voteService.findStatistics();
//	    String endDateStr = statistics.getEndDate();//
//	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    Date enDate = DateUtil.stringToDate(VoteConstant.LIFECYCLE_MAX_STR);
	    Date nowDate = new Date();
	    if (nowDate.after(enDate)) {
	      return "投票已经截至，感谢您的参与！";
	    }
		if(CheckUtil.isEmpty(openid)){
			return "参数错误！";
		}
		WechatUser wechatUser=userService.getUserInfoByOpenid(openid);
		List<Vote> listTodayVote=voteService.findTodayVoteListByOpenid(openid);
		Vote voteSearch = new Vote();
		voteSearch.setPlayer(id);
		voteSearch.setOpenid(openid);
		List<Vote> listTodayVoteOnePlay=voteService.findTodayVoteListByOpenidAndSamePlayer(voteSearch);
		Vote vote=new Vote();
		vote.setOpenid(openid);
		vote.setPlayer(id);
		//check 今日投票次数，今日同一人投票次数
		if(listTodayVote.size()<VoteConstant.VOTE_TIME_MAX_PER_DAY
				&&listTodayVoteOnePlay.size()<VoteConstant.VOTE_TIME_MAX_PER_PLAYER){
			//vote表增加投票记录
			voteService.addVote(vote);
			//player表增加投票数
			voteService.addPlayerVotedNum(id);
			//statistics表增加投票数
			voteService.addTotalVoted();
			return "success";
		}else{
			return "对不起，每天只能给三个人投票，每人一票！";
		}
	}
//		userService.updateVoteWechatuser(wechatUser);
//			Date lastVotedTime=formatDate(wechatUser.getLastVotedTime());
//			Date nowTime=formatDate(new Date());
//			if(lastVotedTime.compareTo(nowTime)==0){
//				if (list.size()<3) {
//					for (Vote v : list) {
//						if(id.equals(v.getPlayer())){
//							return "对不起，每人每天您只能投一次票！";
//						}
//					}
//					//vote表增加投票记录
//					voteService.addVote(vote);
//					//player表增加投票数
//					voteService.addPlayerVotedNum(id);
//					//statistics表增加投票数
//					voteService.addTotalVoted();
//				}else{
//					return "对不起，今天的次数已经用完！";
//				}
//			}else if (lastVotedTime.compareTo(nowTime)==-1) {
//				for (Vote v : list) {
//					if(id.equals(v.getPlayer())){
//						return "对不起，每人每天您只能投一次票！";
//					}
//				}
//				//vote表增加投票记录
//				voteService.addVote(vote);
//				//player表增加投票数
//				voteService.addPlayerVotedNum(id);
//				//statistics表增加投票数
//				voteService.addTotalVoted();
//			}else {
//				return "系统时间错误！";
//			}
//		}
//		//check 今日投票次数，
//		if(CheckUtil.isEmpty(wechatUser.getLastVotedTime())){
//			wechatUser.setVotedPlayer(id);
//			wechatUser.setVotedCount(1);
//			//vote表增加投票记录
//			voteService.addVote(vote);
//			//player表增加投票数
//			voteService.addPlayerVotedNum(id);
//			//statistics表增加投票数
//			voteService.addTotalVoted();
//		}else{
//			Date lastVotedTime=formatDate(wechatUser.getLastVotedTime());
//			Date nowTime=formatDate(new Date());
//			if(lastVotedTime.compareTo(nowTime)==0){
//				if (wechatUser.getVotedCount().intValue()<3) {
//					if(!id.equals(wechatUser.getVotedPlayer())){
//						return "对不起，您只能投票给同一个人";
//					}else {
//						wechatUser.setVotedCount(wechatUser.getVotedCount()+1);
//						//vote表增加投票记录
//						voteService.addVote(vote);
//						//player表增加投票数
//						voteService.addPlayerVotedNum(id);
//						//statistics表增加投票数
//						voteService.addTotalVoted();
//					}
//				}else{
//					return "对不起，今天的次数已经用完！";
//				}
//			}else if (lastVotedTime.compareTo(nowTime)==-1) {
//				if(!id.equals(wechatUser.getVotedPlayer())){
//					return "对不起，您只能投票给同一个人";
//				}else {
//					wechatUser.setVotedCount(1);
//					//vote表增加投票记录
//					voteService.addVote(vote);
//					//player表增加投票数
//					voteService.addPlayerVotedNum(id);
//					//statistics表增加投票数
//					voteService.addTotalVoted();
//				}
//			}else {
//				return "系统时间错误！";
//			}
//		}
//		userService.updateVoteWechatuser(wechatUser);
//		return "success";
	
	//下拉/点击加载
//	<div class="item">
//	<div class="item-content">
//		<div class="box">
//			<div class="pic">
//				<a href="<%=basePath%>/voteinfo.htm?id=${player.id }">
//					<img src="<%=basePath%>/upload/${player.img}" alt="" />
//				</a>
//				<span class="g" style="padding: 2px; display: block; position: absolute; top: 0; left: 0; font-size: 12px; color: #fff; background: rgba(0, 0, 0, 0.5)">编号:${player.id }</span>
//				<span class="g" style="padding: 2px 0; display: block; width: 100%; position: absolute; bottom: 0; left: 0; font-size: 12px; color: #fff; background: rgba(0, 0, 0, 0.5)"></span>
//			</div>
//			<div class="info">
//				<span>${player.name }</span>
//			</div>
//			<div class="btnwarp">
//				<a href="javascript:void(0);" class="btnvote" itemId="${player.id }" propertyId="1">投票(<span class="vc">${player.votedNum }</span>)
//				</a>
//			</div>
//		</div>
//	</div>
//</div>
	@RequestMapping(value="loadVote",produces="application/text;charset=utf-8")
	@ResponseBody
	public String loadVote(Integer page,HttpServletRequest request){
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+ path;
		StringBuilder sb=new StringBuilder();
		List<Player> list=voteService.loadVote(page*10);
		for (Player player : list) {
			sb.append("<div class='item'><div class='item-content'><div class='box'><div class='pic'>");
			sb.append("<a href='"+basePath+"/voteinfo.htm?id="+player.getId()+"'>");
			if(CheckUtil.isEmpty(player.getCompress())){
				sb.append("<img src='"+basePath+"/images/vote/"+player.getImg().split(",")[0]+"' alt='' />");
			}
			else{
				sb.append("<img src='"+basePath+"/images/vote/"+player.getCompress().split(",")[0]+"' alt='' />");
			}
			sb.append("</a>");
			sb.append("<span class='g' style='padding: 2px; display: block; position: absolute; top: 0; left: 0; font-size: 12px; color: #fff; background: rgba(0, 0, 0, 0.5)'>编号:"+player.getId()+"</span>");
			sb.append("<span class='g' style='padding: 0.5px 0; display: block; width: 100%; position: absolute; bottom: 0; left: 0; font-size: 12px; color: #fff; background: rgba(0, 0, 0, 0.5)'></span>");
			sb.append("</div><div class='info'>");
			sb.append("<p style='width:100%;text-align:center'>"+player.getName()+"</p>");
			sb.append("</div><div class='btnwarp'>");
			sb.append("<a href='javascript:void(0);' class='btnvote' itemId='"+player.getId()+"' propertyId='1'>为他加分(<span class='vc'>"+(player.getScore())+"分</span>)");
			sb.append("</a></div></div></div></div>");
		}
		
		return sb.toString();
	}
	
	//player详情
	@RequestMapping("voteinfo")
	public String voteinfo(Long id,Model model,HttpServletRequest request){
		//TODO:测试
		String openid="oQSRbuHYciRcHXmFAEwRJmnKeVzY";
		WechatUser wechatUser=userService.getUserInfoByOpenid(openid);
		if (CheckUtil.isEmpty(openid)) {
			System.out.println("未关注的用户！");
			model.addAttribute("error", "error");
		}
		Player player=voteService.findPlayerById(id);
		
		
//		String openid=(String) WebUtils.getSessionAttribute(request, "openid");
//		WechatUser wechatUser=userService.getUserInfoByOpenid(openid);
//		if (CheckUtil.isEmpty(wechatUser)||wechatUser.getSubscribe().equals(0)) {
//			System.out.println("未关注的用户！");
//			model.addAttribute("error", "error");
//		}
//		Player player=voteService.findPlayerById(id);
//		//距上一名票数差距
//		List<Player> playList=voteService.findRankPlayer();
		
//		Integer rank = player.getRank();

//		Integer diff=0;
//		if (rank>=1) {
//			diff=0;
//		}
//		else {
//			for (int i = 0; i < playList.size(); i++) {
//				if (playList.get(i).getRank()==(rank-1)) {
//					diff=playList.get(i).getVotedNum()-player.getVotedNum();
//				}
//			}
//		}
//		model.addAttribute("diff", diff);
		//图片list
		if (!CheckUtil.isEmpty(player.getCompress())) {
			List<String> compressList = Arrays.asList(player.getCompress().split(","));
			model.addAttribute("compressList", compressList);
		}
		model.addAttribute("player", player);
		model.addAttribute("openid", openid);
		return "vote/info";
	}
	
	//抽奖
	/**
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("voteLottery")
	public String voteLottery(HttpServletRequest request,Model model){
//		String openid=(String) WebUtils.getSessionAttribute(request, "openid");
		String openid="oQSRbuHYciRcHXmFAEwRJmnKeVzY";
		//获取最新一次投票记录
		Vote vote = voteService.getVoteByOpenid(openid);
		//判断是否抽过奖，有则返已经抽过奖弹出，无则向下
		if (vote.getLotteryStatus().equals(VoteConstant.VOTE_HAS_LOTTERY)) {
			return "redirect:vote.htm";
		}
		//运算结果
		Integer resultNum = voteService.getLotteryResult();

		//插入lottery，更新vote
		Lottery lottery = new Lottery();
		lottery.setLotterytype(resultNum);
		lottery.setLotteryname(VoteConstant.LOTTERY_TYPE_NAMEARR[resultNum]);
		lottery.setOpenid(openid);
		lottery.setStatus(1);
		lottery.setVoteid(vote.getId());
		Integer lotteryId = voteService.addLottery(lottery);
		voteService.updateVoteLotteryStatus(vote.getId());
		//返回页面
		model.addAttribute("lottery", lottery);
		model.addAttribute("id", lotteryId);
		
		
		return "vote/lottery";
	}
	
	//抽奖-提交联系电话
	@ResponseBody
	@RequestMapping("voteLotteryMobile")
	public String voteLotteryMobile(Long id,String mobile,HttpServletRequest request,Model model){
//		String openid=(String) WebUtils.getSessionAttribute(request, "openid");
		String openid="oQSRbuHYciRcHXmFAEwRJmnKeVzY";
		//获取抽奖记录
		Lottery lottery = voteService.getLotteryById(id);
		//更新联系电话
		lottery.setMobile(mobile);
		voteService.updateLotteryMobile(lottery);
		//返回
		return "success";
	}
	
	
	//voteUpload
	@RequestMapping("voteUpload")
	public String voteUpload(HttpServletRequest request,Model model){
		String openid=(String) WebUtils.getSessionAttribute(request, "openid");
		WechatUser wechatUser=userService.getUserInfoByOpenid(openid);
		if (CheckUtil.isEmpty(wechatUser)
				||wechatUser.getSubscribe().equals(0)) {
			model.addAttribute("error", "error");
		}
		if (!CheckUtil.isEmpty(openid)) {
			Player player = new Player();
			player.setOpenid(openid);
			if (!CheckUtil.isEmpty(voteService.findPlayerInfo(player))) {
				return "redirect:vote.htm?msg='havejoin'";
			}
		}
		
		
		
		return "vote/upload";
	}
	
	//joinVote
	@RequestMapping("joinVote")
	@ResponseBody
	public String joinVote(Player player,HttpServletRequest request) throws ParseException{
		String openid=(String) WebUtils.getSessionAttribute(request, "openid");
		player.setOpenid(openid);

		Statistics statistics=voteService.findStatistics();
		String endDateStr = statistics.getEndDate();//"2016-03-31 23:59:59"
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    Date enDate = sdf.parse(endDateStr);
	    Date nowDate = new Date();
	    if (nowDate.after(enDate)) {
	      return "redirect:vote.htm?msg='end'";
	    }

		String imgStr = player.getImg();
		if (!CheckUtil.isEmpty(imgStr)) {
			String imgArray[] = imgStr.split(",");
			String compressStr = "";
			for (int i = 0; i < imgArray.length; i++) {
				if(!imgArray[i].contains("webp")&&!imgArray[i].contains("gif")){
					String addimg="";
					if (i==0) {
						addimg="";
					}
					else {
						addimg=",";
					}
					addimg += ((imgArray[i]).split("\\."))[0]+"$2"+"."+((imgArray[i]).split("\\."))[1];
					compressStr +=addimg;
				}
			}
			player.setCompress(compressStr);
		}
		
		/*if(!player.getImg().contains("webp")&&!player.getImg().contains("gif")){
			player.setCompress(((player.getImg()).split("\\."))[0]+"x2"+"."+((player.getImg()).split("\\."))[1]);
		}*/
		voteService.addPlayer(player);
		voteService.addTotalPlayer();
		return "success";
	}
	
	//uploadImg
	@RequestMapping("uploadImg")
	@ResponseBody
	public String uploadImg(Model model,@RequestParam MultipartFile[] myfiles, HttpServletRequest request) throws Exception{
		String img="";
		for (MultipartFile myfile : myfiles) {
			if (myfile.isEmpty()) {
				//TODO
			} else {
				//获得upload路径
				String uploadPath = request.getSession().getServletContext().getRealPath("/upload");
				//文件类型
				System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"+myfile.getOriginalFilename());
				String Imagetype=((myfile.getOriginalFilename()).split("\\."))[1];
				//生成上传后的文件名+后缀
				String fileName=UUID.randomUUID().toString();
				String originalImageName=fileName+"."+Imagetype;
				//保存上传的文件
				FileUtils.copyInputStreamToFile(myfile.getInputStream(),new File(uploadPath, originalImageName));
				if(!Imagetype.contains("webp")&&!Imagetype.contains("gif")){
					//生成缩略图150X170
					ImageCompressUtil.saveMinPhoto(myfile.getInputStream(), uploadPath+"\\"+fileName+"$2."+Imagetype, 1000, 0.9d);
					//ReverseImage.checkReverse(uploadPath+"\\"+fileName+"$2."+Imagetype, 90,null);
					//ImageCompressUtil.zipImageFile(myfile.getInputStream(), 150, 170, 1f, "x2", uploadPath+"\\"+originalImageName);
				}
				img=originalImageName;
			}
		}
		return img;
	}
	public Date formatDate(Date d) throws ParseException{
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		d=sdf.parse(sdf.format(d));
		return d;
	}
	
	@RequestMapping("voteNote")
	public String voteNote(){
		return "vote/votenote";
	}
	@RequestMapping("votePrice")
	public String votePrice(){
		return "vote/voteprice";
	}
	
	@RequestMapping("sub")
	public String sub(){
		return "vote/sub";
	}
	@RequestMapping("voteRank")
	public String voteRank(Model model){
		List<Player> list=voteService.findRankPlayer();
		model.addAttribute("list", list);
		return "vote/voterank";
	}
	@RequestMapping("cc")
	public void cc(){
		List<Player> list=voteService.findRankPlayer();
		for (Player player : list) {
			if(!player.getImg().contains("webp")){
				//ImageCompressUtil.zipImageFile("d:/upload/"+player.getImg(), 150, 170, 1f, "x2");
				player.setCompress(((player.getImg()).split("\\."))[0]+"x2"+"."+((player.getImg()).split("\\."))[1]);
				voteService.updatePlayerC(player);
			}
		}
	}
	
	@RequestMapping("main")
	public String main(){
		return "vote/login";
	}
	
	@RequestMapping("login")
	public String login(String username,String password,Model model,HttpServletRequest request){
		if(CheckUtil.isEmpty(username)||CheckUtil.isEmpty(password)){
			model.addAttribute("msg", "用户名或者密码不能为空！");
			return "vote/login";
		}
		if(!"ldfman@qq.com".equals(username)||!"LDF12345".equals(password)){
			model.addAttribute("msg", "用户名或者密码错误");
			return "vote/login";
		}
		request.getSession().setAttribute("login", "login");
		return "redirect:fixNum.htm";
	}
	
	@RequestMapping("fixNum")
	public String fixNum(Model model,HttpServletRequest request){
		String login=(String) WebUtils.getSessionAttribute(request, "login");
		if(!"login".equals(login)){
			return "redirect:main.htm";
		}
		return "vote/cheat";
	}
	
	@RequestMapping("cheat")
	@ResponseBody
	public String cheat(Integer num,Long id,HttpServletRequest request){
		String login=(String) WebUtils.getSessionAttribute(request, "login");
		if(!"login".equals(login)){
			return "none";
		}
		if(CheckUtil.isEmpty(num)||CheckUtil.isEmpty(id)){
			return "empty";
		}
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("num", num);
		map.put("id", id);
		voteService.cheatTotalVoted(map);
		voteService.cheatPlayerVotedNum(map);
		List<Vote> list=new ArrayList<Vote>();
		for(int i=0;i<num;i++){
			Vote vote=new Vote();
			vote.setOpenid("Cheated!");
			vote.setPlayer(id);
			list.add(vote);
		}
		voteService.cheatVote(list);
		return "success";
	}
}
